use std::{thread, time::Duration};

use ipc_channel::{ipc, ipc::IpcOneShotServer};

fn main() {
    let (server, token) =
        IpcOneShotServer::<String>::new().expect("Failed to create IPC one-shot server");

    println!("token ={}", token);

    let handle = std::thread::spawn(move || {
        let server_name = token;

        let tx: ipc::IpcSender<String> =
            ipc::IpcSender::connect(server_name.to_string()).expect("连接主通道失败");

        for i in 0..10 {
            let msg = format!("主消息 {}", i);
            tx.send(msg.clone()).expect("发送消息失败");
            println!("[子进程] 发送: {}", msg);
        }

        println!("[子进程] 退出");
    });

    let (rx, _) = server.accept().expect("Failed to accept connection");

    println!("[主进程] 收到响应通道");

    for _ in 0..10 {
        if let Ok(msg) = rx.recv() {
            println!("[主进程] 收到: {}", msg);
        }
    }

    println!("[主进程] 退出");

    let _ = handle.join();

    thread::sleep(Duration::from_secs(3));

    let _ = std::process::Command::new("cmd")
        .args(&["/c", "pause"])
        .status();
}
